import { _decorator, Component, Node } from 'cc'
import { TileMapManager } from '../Tile/TileMapManager'
import Levels, { ILevel } from '../../levels'
import { createUINode } from '../../Utils'
import DataManagerInstance from '../../Runtime/DataManager'
import { TILE_HEIGHT, TILE_WIDTH } from '../Tile/TileManager'
import EventManager from '../../Runtime/EventManager'
import { EVENT_ENUM } from '../../Enums'
const { ccclass, property } = _decorator

@ccclass('BattleManager')
export class BattleManager extends Component {
  level: ILevel
  stage: Node

  onLoad() {
    EventManager.Instance.on(EVENT_ENUM.NEXT_LEVEL, this.nextLevel, this)
  }
  onDestroy(): void {
    EventManager.Instance.off(EVENT_ENUM.NEXT_LEVEL, this.nextLevel)
  }

  start() {
    this.generateStage()
    // 生成瓦片地图
    this.initLevel()
  }

  initLevel() {
    const level = Levels[`level${DataManagerInstance.Instance.levelIndex}`]
    if (level) {
      this.clearLevel()
      this.level = level
      DataManagerInstance.Instance.mapInfo = this.level.mapInfo
      DataManagerInstance.Instance.mapRowCount = this.level.mapInfo.length || 0
      DataManagerInstance.Instance.mapColumnCount = this.level.mapInfo[0].length
      this.generateTileMap()
    }
  }

  // 下一关的函数
  nextLevel() {
    DataManagerInstance.Instance.levelIndex++
    this.initLevel()
  }

  clearLevel() {
    this.stage.destroyAllChildren()
    DataManagerInstance.Instance.reset()
  }

  generateStage() {
    // 生成地图父节点
    this.stage = createUINode()
    this.stage.setParent(this.node)
  }

  generateTileMap() {
    // 瓦片节点
    const tileMap = createUINode()
    tileMap.setParent(this.stage)

    // 添加瓦片脚本
    const tileMapManager = tileMap.addComponent(TileMapManager)
    tileMapManager.init()

    this.adaptPos()
  }

  adaptPos() {
    const { mapRowCount, mapColumnCount } = DataManagerInstance.Instance
    console.log('DataManagerInstance:', DataManagerInstance)
    console.log('MapRowCount (from DataManagerInstance):', mapRowCount)
    console.log('MapColumnCount (from DataManagerInstance):', mapColumnCount)

    const disX = (mapRowCount * TILE_WIDTH) / 2
    const disY = (mapColumnCount * TILE_HEIGHT) / 2
    console.log('disX:', disX, 'disY:', disY)

    this.stage.setPosition(-disX, disY)
  }
}
